One of the core principles of any programming language is, "Don't Repeat Yourself". If you have an action that should occur many times, you can define that action once and then call that code whenever you need to carry out that action.
We are already repeating ourselves in our code, so this is a good time to introduce simple functions. Functions mean less work for us as programmers, and effective use of functions results in code that is less error-prone.
In [ ]:
# Let's define a function.
def function_name(argument_1, argument_2):
# Do whatever we want this function to do,
# using argument_1 and argument_2
# Use function_name to call the function.
function_name(value_1, value_2)
This code will not run, but it shows how functions are used in general.
def
, which tells Python that you are about to define a function.current_name
and current_age
, or they can be actual values such as 'eric' and 5.
In [2]:
print("You are doing good work, Adriana!")
print("Thank you very much for your efforts on this project.")
print("\nYou are doing good work, Billy!")
print("Thank you very much for your efforts on this project.")
print("\nYou are doing good work, Caroline!")
print("Thank you very much for your efforts on this project.")
Functions take repeated code, put it in one place, and then you call that code when you want to use it. Here's what the same program looks like with a function.
In [4]:
def thank_you(name):
# This function prints a two-line personalized thank you message.
print("\nYou are doing good work, %s!" % name)
print("Thank you very much for your efforts on this project.")
thank_you('Adriana')
thank_you('Billy')
thank_you('Caroline')
In our original code, each pair of print statements was run three times, and the only difference was the name of the person being thanked. When you see repetition like this, you can usually make your program more efficient by defining a function.
The keyword def tells Python that we are about to define a function. We give our function a name, thank_you() in this case. A variable's name should tell us what kind of information it holds; a function's name should tell us what the variable does. We then put parentheses. Inside these parenthese we create variable names for any variable the function will need to be given in order to do its job. In this case the function will need a name to include in the thank you message. The variable name
will hold the value that is passed into the function thank_you().
To use a function we give the function's name, and then put any values the function needs in order to do its work. In this case we call the function three times, each time passing it a different name.
In [1]:
thank_you('Adriana')
thank_you('Billy')
thank_you('Caroline')
def thank_you(name):
# This function prints a two-line personalized thank you message.
print("\nYou are doing good work, %s!" % name)
print("Thank you very much for your efforts on this project.")
On the first line we ask Python to run the function thank_you(), but Python does not yet know how to do this function. We define our functions at the beginning of our programs, and then we can use them when we need to.
When we introduced the different methods for sorting a list, our code got very repetitive. It takes two lines of code to print a list using a for loop, so these two lines are repeated whenever you want to print out the contents of a list. This is the perfect opportunity to use a function, so let's see how the code looks with a function.
First, let's see the code we had without a function:
In [3]:
students = ['bernice', 'aaron', 'cody']
# Put students in alphabetical order.
students.sort()
# Display the list in its current order.
print("Our students are currently in alphabetical order.")
for student in students:
print(student.title())
# Put students in reverse alphabetical order.
students.sort(reverse=True)
# Display the list in its current order.
print("\nOur students are now in reverse alphabetical order.")
for student in students:
print(student.title())
Here's what the same code looks like, using a function to print out the list:
In [9]:
def show_students(students, message):
# Print out a message, and then the list of students
print(message)
for student in students:
print(student.title())
students = ['bernice', 'aaron', 'cody']
# Put students in alphabetical order.
students.sort()
show_students(students, "Our students are currently in alphabetical order.")
#Put students in reverse alphabetical order.
students.sort(reverse=True)
show_students(students, "\nOur students are now in reverse alphabetical order.")
This is much cleaner code. We have an action we want to take, which is to show the students in our list along with a message. We give this action a name, show_students().
This function needs two pieces of information to do its work, the list of students and a message to display. Inside the function, the code for printing the message and looping through the list is exactly as it was in the non-function code.
Now the rest of our program is cleaner, because it gets to focus on the things we are changing in the list, rather than having code for printing the list. We define the list, then we sort it and call our function to print the list. We sort it again, and then call the printing function a second time, with a different message. This is much more readable code.
For a quick example, let's say we decide our printed output would look better with some form of a bulleted list. Without functions, we'd have to change each print statement. With a function, we change just the print statement in the function:
In [10]:
def show_students(students, message):
# Print out a message, and then the list of students
print(message)
for student in students:
print("- " + student.title())
students = ['bernice', 'aaron', 'cody']
# Put students in alphabetical order.
students.sort()
show_students(students, "Our students are currently in alphabetical order.")
#Put students in reverse alphabetical order.
students.sort(reverse=True)
show_students(students, "\nOur students are now in reverse alphabetical order.")
You can think of functions as a way to "teach" Python some new behavior. In this case, we taught Python how to create a list of students using hyphens; now we can tell Python to do this with our students whenever we want to.
In [3]:
def get_number_word(number):
# Takes in a numerical value, and returns
# the word corresponding to that number.
if number == 1:
return 'one'
elif number == 2:
return 'two'
elif number == 3:
return 'three'
# ...
# Let's try out our function.
for current_number in range(0,4):
number_word = get_number_word(current_number)
print(current_number, number_word)
It's helpful sometimes to see programs that don't quite work as they are supposed to, and then see how those programs can be improved. In this case, there are no Python errors; all of the code has proper Python syntax. But there is a logical error, in the first line of the output.
We want to either not include 0 in the range we send to the function, or have the function return something other than None
when it receives a value that it doesn't know. Let's teach our function the word 'zero', but let's also add an else
clause that returns a more informative message for numbers that are not in the if-chain.m
In [5]:
def get_number_word(number):
# Takes in a numerical value, and returns
# the word corresponding to that number.
if number == 0:
return 'zero'
elif number == 1:
return 'one'
elif number == 2:
return 'two'
elif number == 3:
return 'three'
else:
return "I'm sorry, I don't know that number."
# Let's try out our function.
for current_number in range(0,6):
number_word = get_number_word(current_number)
print(current_number, number_word)
If you use a return statement in one of your functions, keep in mind that the function stops executing as soon as it hits a return statement. For example, we can add a line to the get_number_word() function that will never execute, because it comes after the function has returned a value:
In [7]:
def get_number_word(number):
# Takes in a numerical value, and returns
# the word corresponding to that number.
if number == 0:
return 'zero'
elif number == 1:
return 'one'
elif number == 2:
return 'two'
elif number == 3:
return 'three'
else:
return "I'm sorry, I don't know that number."
# This line will never execute, because the function has already
# returned a value and stopped executing.
print("This message will never be printed.")
# Let's try out our function.
for current_number in range(0,6):
number_word = get_number_word(current_number)
print(current_number, number_word)
There is much more to learn about functions, but we will get to those details later. For now, feel free to use functions whenever you find yourself writing the same code several times in a program. Some of the things you will learn when we focus on functions:
for
loop.
In [ ]:
# Ex 4.1 : Greeter
# put your code here
In [ ]:
# Ex 4.2 : Full Names
# put your code here
In [ ]:
# Ex 4.3 : Addition Calculator
# put your code here
In [ ]:
# Ex 4.4 : Return Calculator
# put your code here
In [ ]:
# Ex 4.5 : List Exercises - Functions
# put your code here
In [ ]:
# Challenge: Lyrics
# Put your code here